package com.jghz.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import com.bstek.bdf2.core.context.ContextHolder;

@Controller
public class LoginController {

	@GetMapping("/")
	public String toIndex(HttpServletRequest request, Model model) throws IOException {
		if (ContextHolder.getHttpSession().getAttribute(ContextHolder.LOGIN_USER_SESSION_KEY) != null)
			return "redirect:/bdf2.core.view.frame.main.MainFrame2.d";
		else
			return "redirect:/index";
	}

	@GetMapping("/index")
	public String index(Model model) throws IOException {
		return "index";
	}

	@GetMapping("/login")
	public String login(Model model) throws IOException {
		String error = getAuthenticationExceptionMessage();
		if (StringUtils.isNotEmpty(error)) {
			System.out.println("Login Error:" + error);
			model.addAttribute("error", "error");
		}
		return "login";
	}

	private String getAuthenticationExceptionMessage() {
		Exception exp = (Exception) ContextHolder.getHttpSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
		if (exp == null) {
			exp = (Exception) ContextHolder.getRequest().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
		}
		if (exp != null)
			return exp.getMessage();
		return null;
	}

}
